<template>
  <div class="model-market-container">
    <n-card class="market-card">
      <template #header>
        <div class="card-header">
          <h1>AI模型市场</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="market-content">
        <div class="search-filters">
          <n-input-group>
            <n-input 
              v-model:value="searchQuery" 
              placeholder="搜索模型..." 
              clearable
              @keydown.enter="searchModels"
            />
            <n-button type="primary" @click="searchModels">
              <template #icon><n-icon><SearchOutline /></n-icon></template>
              搜索
            </n-button>
          </n-input-group>
          
          <div class="filter-section">
            <n-space vertical>
              <n-space>
                <n-select 
                  v-model:value="filters.category" 
                  placeholder="分类" 
                  :options="categoryOptions"
                  clearable
                  style="width: 150px;"
                />
                <n-select 
                  v-model:value="filters.type" 
                  placeholder="类型" 
                  :options="typeOptions"
                  clearable
                  style="width: 150px;"
                />
                <n-select 
                  v-model:value="filters.sortBy" 
                  placeholder="排序方式" 
                  :options="sortOptions"
                  style="width: 150px;"
                />
                <n-switch v-model:value="filters.onlyFree">
                  <template #checked>仅免费</template>
                  <template #unchecked>全部</template>
                </n-switch>
              </n-space>
              <n-space>
                <n-tag 
                  v-for="tag in activeTags" 
                  :key="tag.key" 
                  closable 
                  @close="removeFilter(tag.key)"
                >
                  {{ tag.label }}
                </n-tag>
                <n-button text size="small" v-if="activeTags.length > 0" @click="clearFilters">
                  清除全部
                </n-button>
              </n-space>
            </n-space>
          </div>
        </div>
        
        <n-divider />
        
        <div class="models-section">
          <div class="section-header">
            <h2>{{ currentCategory }}</h2>
            <span>共 {{ filteredModels.length }} 个模型</span>
          </div>
          
          <div v-if="loading" class="loading-container">
            <n-spin size="large" />
            <p>正在加载模型...</p>
          </div>
          
          <div v-else-if="filteredModels.length === 0" class="empty-container">
            <n-empty description="未找到符合条件的模型">
              <template #extra>
                <n-button @click="clearFilters">清除筛选条件</n-button>
              </template>
            </n-empty>
          </div>
          
          <div v-else class="models-grid">
            <n-card
              v-for="model in filteredModels"
              :key="model.id"
              class="model-card"
              :class="{ 'model-featured': model.featured }"
              hoverable
              @click="showModelDetail(model)"
            >
              <div class="model-thumbnail">
                <img :src="model.thumbnail" :alt="model.name" />
                <div class="model-badges">
                  <n-tag v-if="model.price === 0" type="success" size="small">免费</n-tag>
                  <n-tag v-else type="warning" size="small">{{ model.price }} 积分</n-tag>
                  <n-tag v-if="model.featured" type="primary" size="small">精选</n-tag>
                </div>
              </div>
              <div class="model-info">
                <h3>{{ model.name }}</h3>
                <p class="model-description">{{ model.description }}</p>
                <div class="model-meta">
                  <div class="model-rating">
                    <n-rate :value="model.rating" readonly size="small" />
                    <span>{{ model.rating.toFixed(1) }} ({{ model.ratingCount }})</span>
                  </div>
                  <div class="model-creator">
                    <n-avatar :src="model.creatorAvatar" round size="small" />
                    <span>{{ model.creator }}</span>
                  </div>
                </div>
                <div class="model-tags">
                  <n-tag v-for="tag in model.tags.slice(0, 3)" :key="tag" size="small">{{ tag }}</n-tag>
                  <span v-if="model.tags.length > 3">+{{ model.tags.length - 3 }}</span>
                </div>
              </div>
            </n-card>
          </div>
          
          <n-pagination 
            v-if="filteredModels.length > 0"
            v-model:page="currentPage"
            :page-count="totalPages"
            :page-slot="5"
            show-size-picker
            :page-sizes="[12, 24, 48]"
            v-model:page-size="pageSize"
          />
        </div>
      </div>
    </n-card>
    
    <!-- 模型详情对话框 -->
    <n-modal
      v-model:show="modelDetailVisible"
      preset="card"
      style="width: 700px"
      :title="selectedModel?.name || '模型详情'"
      :bordered="false"
    >
      <div v-if="selectedModel" class="model-detail">
        <div class="model-detail-header">
          <div class="model-detail-thumbnail">
            <img :src="selectedModel.thumbnail" :alt="selectedModel.name" />
          </div>
          <div class="model-detail-info">
            <div class="model-detail-meta">
              <n-tag v-if="selectedModel.price === 0" type="success">免费</n-tag>
              <n-tag v-else type="warning">{{ selectedModel.price }} 积分</n-tag>
              <n-tag>{{ selectedModel.category }}</n-tag>
              <n-tag>{{ selectedModel.type }}</n-tag>
            </div>
            <div class="model-detail-rating">
              <n-rate :value="selectedModel.rating" readonly />
              <span>{{ selectedModel.rating.toFixed(1) }} ({{ selectedModel.ratingCount }}评价)</span>
            </div>
            <div class="model-detail-creator">
              <n-avatar :src="selectedModel.creatorAvatar" round />
              <span>{{ selectedModel.creator }}</span>
            </div>
            <div class="model-detail-stats">
              <div class="stat-item">
                <n-icon><DownloadOutline /></n-icon>
                <span>{{ selectedModel.downloads }} 下载</span>
              </div>
              <div class="stat-item">
                <n-icon><TimeOutline /></n-icon>
                <span>{{ formatDate(selectedModel.updateDate) }} 更新</span>
              </div>
            </div>
            <div class="model-detail-actions">
              <n-button
                type="primary"
                @click="downloadModel(selectedModel)"
                :loading="downloading"
                :disabled="downloading"
              >
                <template #icon><n-icon><CloudDownloadOutline /></n-icon></template>
                {{ selectedModel.price === 0 ? '免费下载' : '购买并下载' }}
              </n-button>
              <n-button @click="previewModel(selectedModel)">
                <template #icon><n-icon><EyeOutline /></n-icon></template>
                预览效果
              </n-button>
            </div>
          </div>
        </div>
        
        <n-divider />
        
        <div class="model-detail-description">
          <h3>模型描述</h3>
          <p>{{ selectedModel.fullDescription }}</p>
        </div>
        
        <div class="model-detail-samples">
          <h3>效果示例</h3>
          <div class="samples-grid">
            <div v-for="(sample, index) in selectedModel.samples" :key="index" class="sample-item">
              <img :src="sample.image" :alt="`示例 ${index + 1}`" @click="previewSample(sample)" />
            </div>
          </div>
        </div>
        
        <div class="model-detail-specs">
          <h3>技术规格</h3>
          <n-descriptions bordered>
            <n-descriptions-item label="大小">{{ formatSize(selectedModel.size) }}</n-descriptions-item>
            <n-descriptions-item label="版本">{{ selectedModel.version }}</n-descriptions-item>
            <n-descriptions-item label="训练数据集">{{ selectedModel.trainingDataset }}</n-descriptions-item>
            <n-descriptions-item label="兼容版本">{{ selectedModel.compatibleVersions }}</n-descriptions-item>
            <n-descriptions-item label="许可协议">{{ selectedModel.license }}</n-descriptions-item>
            <n-descriptions-item label="处理位置">{{ selectedModel.processingLocation }}</n-descriptions-item>
          </n-descriptions>
        </div>
        
        <div class="model-detail-reviews">
          <h3>用户评价</h3>
          <n-list>
            <n-list-item v-for="review in selectedModel.reviews.slice(0, 3)" :key="review.id">
              <n-thing
                :title="review.username"
                :description="formatDate(review.date)"
              >
                <template #avatar>
                  <n-avatar :src="review.avatar" round />
                </template>
                <template #header-extra>
                  <n-rate :value="review.rating" readonly size="small" />
                </template>
                <template #default>
                  <p>{{ review.comment }}</p>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
          <n-button v-if="selectedModel.reviews.length > 3" text>查看全部 {{ selectedModel.reviews.length }} 条评价</n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NIcon,
  NSpace,
  NInput,
  NInputGroup,
  NSelect,
  NSwitch,
  NTag,
  NDivider,
  NSpin,
  NEmpty,
  NRate,
  NAvatar,
  NPagination,
  NModal,
  NDescriptions,
  NDescriptionsItem,
  NList,
  NListItem,
  NThing
} from 'naive-ui'
import {
  ArrowBackOutline,
  SearchOutline,
  DownloadOutline,
  TimeOutline,
  CloudDownloadOutline,
  EyeOutline
} from '@vicons/ionicons5'

// 定义类型
interface FilterTag {
  key: string;
  label: string;
}

interface ModelReview {
  id: number;
  username: string;
  avatar: string;
  rating: number;
  date: Date;
  comment: string;
}

interface ModelSample {
  image: string;
}

interface AIModel {
  id: number;
  name: string;
  description: string;
  fullDescription: string;
  category: string;
  type: string;
  price: number;
  rating: number;
  ratingCount: number;
  downloads: number;
  creator: string;
  creatorAvatar: string;
  thumbnail: string;
  tags: string[];
  featured: boolean;
  updateDate: Date;
  version: string;
  size: number;
  trainingDataset: string;
  compatibleVersions: string;
  license: string;
  processingLocation: string;
  samples: ModelSample[];
  reviews: ModelReview[];
}

const router = useRouter()
const message = useMessage()

// 搜索和筛选
const searchQuery = ref('')
const filters = reactive({
  category: null as string | null,
  type: null as string | null,
  sortBy: 'rating' as string,
  onlyFree: false
})

// 分页
const currentPage = ref(1)
const pageSize = ref(12)

// 加载状态
const loading = ref(true)
const downloading = ref(false)

// 模型详情
const modelDetailVisible = ref(false)
const selectedModel = ref<AIModel | null>(null)

// 选项数据
const categoryOptions = [
  { label: '角色模型', value: 'character' },
  { label: '场景模型', value: 'scene' },
  { label: '动作模型', value: 'action' },
  { label: '对话模型', value: 'dialogue' }
]

const typeOptions = [
  { label: '生成式', value: 'generative' },
  { label: '微调型', value: 'finetuned' },
  { label: '基础模型', value: 'base' },
  { label: '专家型', value: 'expert' }
]

const sortOptions = [
  { label: '评分', value: 'rating' },
  { label: '下载量', value: 'downloads' },
  { label: '最新', value: 'newest' },
  { label: '价格', value: 'price' }
]

// 模型数据
const models = ref<AIModel[]>([
  {
    id: 1,
    name: '古风角色生成器',
    description: '生成古代风格的人物角色描述，适合古装剧和武侠作品。',
    fullDescription: '这个模型专门针对中国古代人物形象进行了训练，可以生成栩栩如生的古代人物角色描述。包括各个朝代的服饰特点、言谈举止和社会背景等。适合用于古装剧、武侠小说、历史题材作品的角色设计。支持多种角色类型，如文人、武将、商人、艺伴等，并能根据提示词生成符合历史背景的角色形象。',
    category: '角色模型',
    type: '微调型',
    price: 0,
    rating: 4.7,
    ratingCount: 128,
    downloads: 3542,
    creator: '云梦工坊',
    creatorAvatar: 'https://picsum.photos/id/1005/50/50',
    thumbnail: 'https://picsum.photos/id/1035/300/200',
    tags: ['古风', '角色', '微调模型', '免费'],
    featured: true,
    updateDate: new Date(2023, 9, 15),
    version: '1.2.3',
    size: 256000000,
    trainingDataset: '古代文学作品集、历史人物志',
    compatibleVersions: '1.0.0 及以上版本',
    license: '创作共用 CC-BY-4.0',
    processingLocation: '本地/云端',
    samples: [
      { image: 'https://picsum.photos/id/1027/300/200' },
      { image: 'https://picsum.photos/id/1028/300/200' },
      { image: 'https://picsum.photos/id/1029/300/200' }
    ],
    reviews: [
      {
        id: 101,
        username: '清风明月',
        avatar: 'https://picsum.photos/id/1012/50/50',
        rating: 5,
        date: new Date(2023, 9, 20),
        comment: '生成的角色非常有古风韵味，细节丰富，对我的创作帮助很大。'
      },
      {
        id: 102,
        username: '剑客无名',
        avatar: 'https://picsum.photos/id/1013/50/50',
        rating: 4,
        date: new Date(2023, 9, 18),
        comment: '生成的武将形象很到位，但文人形象稍显刻板，总体很满意。'
      },
      {
        id: 103,
        username: '墨香书生',
        avatar: 'https://picsum.photos/id/1014/50/50',
        rating: 5,
        date: new Date(2023, 9, 16),
        comment: '模型的服饰细节非常准确，连不同朝代的差异都能体现出来，专业度很高。'
      }
    ]
  },
  {
    id: 2,
    name: '自然场景生成专家',
    description: '生成详细的自然环境场景描述，包括各种地形、气候和光照条件。',
    fullDescription: '自然场景生成专家基于大量风景照片和环境描述训练而成，能够生成极其详细的自然环境描述。从茂密森林到广袤沙漠，从宁静湖泊到壮丽山脉，模型可以创建丰富多样的自然场景。特别适合需要大量环境描述的创作者使用。模型还能根据时间、季节和天气条件调整场景描述，创造出不同氛围的环境。',
    category: '场景模型',
    type: '专家型',
    price: 200,
    rating: 4.9,
    ratingCount: 245,
    downloads: 1876,
    creator: '景天工作室',
    creatorAvatar: 'https://picsum.photos/id/1006/50/50',
    thumbnail: 'https://picsum.photos/id/10/300/200',
    tags: ['自然', '场景', '环境', '专业'],
    featured: true,
    updateDate: new Date(2023, 10, 5),
    version: '2.0.1',
    size: 385000000,
    trainingDataset: '自然地理数据库、风景摄影集',
    compatibleVersions: '1.5.0 及以上版本',
    license: '商业授权',
    processingLocation: '本地/云端',
    samples: [
      { image: 'https://picsum.photos/id/15/300/200' },
      { image: 'https://picsum.photos/id/16/300/200' },
      { image: 'https://picsum.photos/id/17/300/200' }
    ],
    reviews: [
      {
        id: 201,
        username: '自然观察者',
        avatar: 'https://picsum.photos/id/1015/50/50',
        rating: 5,
        date: new Date(2023, 10, 10),
        comment: '生成的场景描述细节丰富，光影效果描绘得尤为出色，非常适合我的风景动画创作。'
      },
      {
        id: 202,
        username: '漫游笔记',
        avatar: 'https://picsum.photos/id/1016/50/50',
        rating: 5,
        date: new Date(2023, 10, 8),
        comment: '值得每一分钱！生成的描述几乎可以直接用于我的作品中，省去了大量构思时间。'
      }
    ]
  }
])

// 计算属性
const currentCategory = computed(() => {
  return filters.category ? 
    categoryOptions.find(c => c.value === filters.category)?.label : 
    '所有模型'
})

const activeTags = computed((): FilterTag[] => {
  const tags: FilterTag[] = []
  
  if (filters.category) {
    const category = categoryOptions.find(c => c.value === filters.category)
    if (category) {
      tags.push({ key: 'category', label: `分类: ${category.label}` })
    }
  }
  
  if (filters.type) {
    const type = typeOptions.find(t => t.value === filters.type)
    if (type) {
      tags.push({ key: 'type', label: `类型: ${type.label}` })
    }
  }
  
  if (filters.onlyFree) {
    tags.push({ key: 'onlyFree', label: '仅免费' })
  }
  
  if (searchQuery.value) {
    tags.push({ key: 'search', label: `搜索: ${searchQuery.value}` })
  }
  
  return tags
})

const filteredModels = computed(() => {
  let result = [...models.value]
  
  // 应用搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(model => 
      model.name.toLowerCase().includes(query) || 
      model.description.toLowerCase().includes(query) ||
      model.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }
  
  // 应用筛选
  if (filters.category) {
    result = result.filter(model => model.category === categoryOptions.find(c => c.value === filters.category)?.label)
  }
  
  if (filters.type) {
    result = result.filter(model => model.type === typeOptions.find(t => t.value === filters.type)?.label)
  }
  
  if (filters.onlyFree) {
    result = result.filter(model => model.price === 0)
  }
  
  // 应用排序
  if (filters.sortBy === 'rating') {
    result.sort((a, b) => b.rating - a.rating)
  } else if (filters.sortBy === 'downloads') {
    result.sort((a, b) => b.downloads - a.downloads)
  } else if (filters.sortBy === 'newest') {
    result.sort((a, b) => new Date(b.updateDate).getTime() - new Date(a.updateDate).getTime())
  } else if (filters.sortBy === 'price') {
    result.sort((a, b) => a.price - b.price)
  }
  
  return result
})

const totalPages = computed(() => Math.ceil(filteredModels.value.length / pageSize.value))

// 方法
const searchModels = () => {
  currentPage.value = 1
  // 实际项目中这里可能需要调用API
}

const clearFilters = () => {
  searchQuery.value = ''
  filters.category = null
  filters.type = null
  filters.onlyFree = false
  filters.sortBy = 'rating'
  currentPage.value = 1
}

const removeFilter = (key: string) => {
  if (key === 'category') {
    filters.category = null
  } else if (key === 'type') {
    filters.type = null
  } else if (key === 'onlyFree') {
    filters.onlyFree = false
  } else if (key === 'search') {
    searchQuery.value = ''
  }
}

const showModelDetail = (model: AIModel) => {
  selectedModel.value = model
  modelDetailVisible.value = true
}

const downloadModel = async (model: AIModel) => {
  if (model.price > 0) {
    // 处理购买逻辑
    const confirmed = window.confirm(`确定要使用 ${model.price} 积分购买此模型吗？`)
    if (!confirmed) return
  }
  
  downloading.value = true
  
  try {
    // 模拟下载过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    message.success(`模型"${model.name}"下载成功`)
    // 这里应该有实际的下载和安装逻辑
  } catch (error) {
    message.error('下载失败，请重试')
    console.error(error)
  } finally {
    downloading.value = false
  }
}

const previewModel = (model: AIModel) => {
  message.info('正在准备预览...')
  // 这里应该有模型预览逻辑
}

const previewSample = (sample: ModelSample) => {
  // 这里应该有样本预览逻辑，例如显示大图
}

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric'
  })
}

const formatSize = (bytes: number) => {
  if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(2) + ' KB'
  } else if (bytes < 1024 * 1024 * 1024) {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  } else {
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
  }
}

const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(async () => {
  // 模拟API请求
  try {
    await new Promise(resolve => setTimeout(resolve, 1500))
    // 在实际项目中，这里会从API获取模型数据
    loading.value = false
  } catch (error) {
    message.error('加载模型数据失败')
    console.error(error)
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.model-market-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .market-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .market-content {
    margin-top: 20px;
    
    .search-filters {
      margin-bottom: 20px;
      
      .filter-section {
        margin-top: 16px;
      }
    }
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h2 {
        margin: 0;
        font-size: 20px;
      }
    }
    
    .loading-container,
    .empty-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      min-height: 300px;
    }
    
    .models-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
      
      .model-card {
        border: 1px solid var(--border-color);
        transition: transform 0.2s, box-shadow 0.2s;
        height: 100%;
        display: flex;
        flex-direction: column;
        
        &.model-featured {
          border-color: var(--primary-color);
        }
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .model-thumbnail {
          position: relative;
          height: 150px;
          overflow: hidden;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .model-badges {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 5px;
          }
        }
        
        .model-info {
          flex: 1;
          padding: 15px;
          display: flex;
          flex-direction: column;
          
          h3 {
            margin: 0 0 10px 0;
            font-size: 16px;
          }
          
          .model-description {
            color: var(--text-color-3);
            font-size: 14px;
            margin-bottom: 15px;
            flex: 1;
            
            // 最多显示3行
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .model-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            
            .model-rating,
            .model-creator {
              display: flex;
              align-items: center;
              gap: 5px;
              font-size: 12px;
            }
          }
          
          .model-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            
            span {
              font-size: 12px;
              color: var(--text-color-3);
            }
          }
        }
      }
    }
  }
  
  // 模型详情对话框样式
  .model-detail {
    &-header {
      display: grid;
      grid-template-columns: 300px 1fr;
      gap: 20px;
      margin-bottom: 20px;
      
      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }
      
      .model-detail-thumbnail {
        height: 200px;
        overflow: hidden;
        border-radius: 4px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .model-detail-info {
        display: flex;
        flex-direction: column;
        gap: 15px;
        
        .model-detail-meta,
        .model-detail-stats {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }
        
        .model-detail-rating,
        .model-detail-creator {
          display: flex;
          align-items: center;
          gap: 10px;
        }
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 5px;
          color: var(--text-color-3);
          font-size: 14px;
        }
        
        .model-detail-actions {
          margin-top: auto;
          display: flex;
          gap: 10px;
        }
      }
    }
    
    &-description,
    &-samples,
    &-specs,
    &-reviews {
      margin-bottom: 25px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 15px;
        font-size: 18px;
      }
    }
    
    .samples-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 10px;
      
      .sample-item {
        cursor: pointer;
        border-radius: 4px;
        overflow: hidden;
        transition: transform 0.2s;
        
        &:hover {
          transform: scale(1.05);
        }
        
        img {
          width: 100%;
          height: 100px;
          object-fit: cover;
        }
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .model-market-container .market-content .models-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}
</style> 